<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>history路由处理</title>
</head>
<body>
    
    <div id="nav">

        <a href="/page1" class="page">page1</a>
        <a href="/page2" class="page">page2</a>
        <a href="/page3" class="page">page3</a>

    </div>

    <div id="container"></div>

    <script>

        class HistoryRouter {

            constructor() {

                this.historyRouterObj = {};

                this.listenLink();
                this.listenPopState();

            }

            listenPopState() {

                // popstate 事件
                window.addEventListener('popstate',e => {

                    let state = e.state || {};
                    let path = state.path || '';

                    this.dealPathHander(path);

                })
            }



            listenLink() {

                // 将监听事件注册到全局
                window.addEventListener('click',e => {
                    
                    let dom = e.target;
                    let path = dom.getAttribute('href'); 
                    if(dom.nodeName == 'A' && path) {

                        // 阻止在 a 标签上的默认事件
                        e.preventDefault();
                        
                        this.assign(path);

                        this.dealPathHander(path);
                        
                    }
                    
                })
            }

            // 通过 history 更改浏览器上显示的url
            assign(path) {

                history.pushState({path},null,path); // 对象，title，url

            }

            // 挂载相应路由的内容
            dealPathHander(path){

                this.historyRouterObj[path]();
            }

            // 将路由和路由对应的挂载函数插入到实例的 historyRouterObj 对象中
            register(path,callback=function() {}) {

                this.historyRouterObj[path] = callback.bind(this);
            }
        }



        console.log('开始');
        // 创建一个 HistoryRouter 实例
        let router = new HistoryRouter();
        let container = document.getElementById('container');

        console.log('注册路由');
        // 在 HistoryRouter 实例中注册路由
        router.register('/page1',() => {

            container.innerHTML = '我是page1';
        })

        router.register('/page2',() => {
            container.innerHTML = '我是page2';
        })
        router.register('/page3',() => {
            container.innerHTML = '我是page3';
        })



    </script>
</body>
</html>